//
//  ConfirmEmailView.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/6/25.
//

import UIKit

class ConfirmEmailView: UIView {
    let resendBtn = ViewFactory.shared.generateButtonOnAlertView()
    var timer : Timer?
    var successClosure: ((_ msg: String)->Void)?
    var content: String = ""
    var countDownKey: String = ""
    var countDownSeconds: Int = 0
    init(conent: String, closure: ((_ msg: String)->Void)?) {
        super.init(frame: CGRect.zero)
        self.content = conent
        self.setUpView()
        self.successClosure = closure
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setUpView() {
        self.backgroundColor = UIColor(hexStr: "#00000080")
        //back view
        let backView = UIView()
        backView.backgroundColor = UIColor.white
        self.addSubview(backView)
        backView.layer.cornerRadius = Constant.BackViewCornerRadius
        backView.snp.makeConstraints { (make) in
            make.width.equalTo(300)
            make.height.greaterThanOrEqualTo(0)
            make.centerX.centerY.equalToSuperview()
        }
        
        //version info
        let msgLabel = BaseLabel()
        msgLabel.text = self.content
        msgLabel.textAlignment = NSTextAlignment.left
        msgLabel.setFont(R.font.interRegular(size: 15))
        msgLabel.textColor = .black
        msgLabel.numberOfLines = 0
        msgLabel.lineBreakMode = .byTruncatingTail
        backView.addSubview(msgLabel)
        msgLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(15)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.greaterThanOrEqualTo(0)
        }
        //horizonal line view
        let lineView = UIView()
        lineView.backgroundColor = UIColor(red: 0.86, green: 0.86, blue: 0.86, alpha: 1)
        backView.addSubview(lineView)
        lineView.snp.makeConstraints { (make) in
            make.top.equalTo(msgLabel.snp.bottom).offset(20)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        //vertial line view
        let lineView1 = UIView()
        lineView1.backgroundColor = UIColor(red: 0.86, green: 0.86, blue: 0.86, alpha: 1)
        backView.addSubview(lineView1)
        lineView1.snp.makeConstraints { (make) in
            make.top.equalTo(lineView.snp.bottom)
            make.height.equalTo(57)
            make.width.equalTo(1)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        //No button
        backView.addSubview(resendBtn)
        resendBtn.snp.makeConstraints { (make) in
            make.top.equalTo(lineView)
            make.left.equalToSuperview()
            make.right.equalTo(lineView1)
            make.bottom.equalToSuperview()
        }
        
        //Yes button
        let yesBtn = ViewFactory.shared.generateButtonOnAlertView(R.string.localizable.oK())
        backView.addSubview(yesBtn)
        yesBtn.snp.makeConstraints { (make) in
            make.top.equalTo(lineView)
            make.left.equalTo(lineView1)
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        yesBtn.addTarget(self, action: #selector(yesBtnClick), for: UIControl.Event.touchUpInside)
        resendBtn.addTarget(self, action: #selector(resendBtnClick), for: UIControl.Event.touchUpInside)
        
        self.initData()
    }
    private func initData(){
        self.countDownKey = (APPConfig.loginInfo.email) + "ForConfirmEmail"
        self.getCurrentTimeForCountDown()
    }
    @objc func resendBtnClick(){
        self.sendConfirmEmail()
    }
    @objc func yesBtnClick(){
        self.removeFromSuperview()
    }
    fileprivate func setResendBtnTitle(_ title: String,enabled: Bool){
        resendBtn.setTitle(title, for: UIControl.State.normal)
        resendBtn.isEnabled = enabled
    }
    
    fileprivate func getCurrentTimeForCountDown(){
        if let dateStr = UserDefaults.standard.object(forKey: self.countDownKey) as? String {
            let dateFormatter = DateFormatter()
            let locale = Locale(identifier: "en-au")//en是语言码，au是地区码，覆盖设备上语言和地区的设置
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
            dateFormatter.locale = locale
            if let beginDate = dateFormatter.date(from: dateStr) {
                let components = Calendar.current.dateComponents([.second], from: beginDate, to: Date())
                if let toNowSecond = components.second, toNowSecond < APPConfig.ConfirmEmailInterval {
                    self.countDownSeconds = APPConfig.ConfirmEmailInterval - toNowSecond
                    self.startTimer()
                }else{
                    //有UserDefaults.standard.object(forKey: self.countDownKey)标识发送过，按钮显示为resend
                    self.setResendBtnTitle("Resend",enabled: true)
                }
            }
        }else{
            self.setResendBtnTitle("Send",enabled: true)
        }
    }
    @objc func startTimer() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(refreshCountDown), userInfo: nil, repeats: true)
        //调用fire()会立即启动计时器
        timer!.fire()
    }
    @objc func stopTimer() {
        if timer != nil {
            timer!.invalidate() //销毁timer
            timer = nil
        }
    }

    @objc func refreshCountDown(){
        if self.countDownSeconds == 0 {
            self.setResendBtnTitle("Resend",enabled: true)
            self.stopTimer()
        }else{
            self.countDownSeconds = self.countDownSeconds - 1
            self.setResendBtnTitle("\(self.countDownSeconds)s Resend",enabled: false)
        }
    }
    func sendConfirmEmail(){
        if  Connectivity.isConnectedToInternet {
            let viewModel = LoginService()
            viewModel.setBlockAfterNetwork({ (result , _) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                if let msg = result as? String{
                    self.saveCurrentTimeForCountDown()
                    self.stopTimer()
                    self.removeFromSuperview()
                    self.successClosure?(msg)
                    
                }
            }) { (code,error) -> Void in
                ModelViewUtil.shared.hideLoadingView()
                Tool().showErrorInfo(code,error)
            }
            //add Loading view
            ModelViewUtil.shared.showLoadingView(NSLocalizedString("Sending..." , comment: ""))
            viewModel.sendConfirmEmail()
        }else{
            Tool().showFailureInfo()
        }
    }
    func saveCurrentTimeForCountDown(){
        //记录发送时间
        let dateFormatter = DateFormatter()
        let locale = Locale(identifier: "en-au")//en是语言码，au是地区码，覆盖设备上语言和地区的设置
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dateFormatter.locale = locale
        let currentDateStr = dateFormatter.string(from: Date())
        UserDefaults.standard.set(currentDateStr, forKey: self.countDownKey)
    }
}
